package cosplay.Controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

import cosplay.Beans.Photos;
import cosplay.DAO.AlbumDAOImpl;
import cosplay.DAO.CompetitionDAOImpl;
import cosplay.DAO.PhotoDAOImpl;
import cosplay.DAO.CompetitionDetailDAOImpl;
import cosplay.DAO.UserDAOImpl;
import cosplay.Services.CacheServices;
import cosplay.Services.CommonServices;
import cosplay.Services.PhotoServices;
@Controller (value="photocontroler")
public class PhotoController extends MultiActionController {
	@Autowired
	private PhotoDAOImpl photodao;
	@Autowired
	private UserDAOImpl userdao;
	@Autowired
	private CompetitionDAOImpl competitiondao;
	@Autowired
	private CompetitionDetailDAOImpl detaildao;
	@Autowired
	private AlbumDAOImpl albumdao;
	private Cache cache=CacheManager.create().getCache("COSPLAY_CACHE");

	@RequestMapping(value="/addphoto.htm",method=RequestMethod.GET)
	protected ModelAndView handleShowAdd(HttpServletRequest req,
			HttpServletResponse res) throws Exception {
		// TODO Auto-generated method stub
		int albumid=CommonServices.getIDFromRequest(req, "albumid");
		ModelMap model =new ModelMap();
		model.addAttribute("target","addphoto.htm");
		model.addAttribute("albumid",albumid);
		model.addAttribute("message","please enter infomation");
		return new ModelAndView("photoupload","model",model);
	}
	
	@RequestMapping(value="/addphoto.htm",method=RequestMethod.POST)
	protected ModelAndView handelActAdd(HttpServletRequest req, HttpServletResponse res)throws Exception
	{
		Photos photo=getPhotoFromReq((MultipartHttpServletRequest) req);
		int id=photodao.add(photo);
		ModelMap model=new ModelMap();
		if (id>0)
		{
			res.setIntHeader("sucess", 1);
			res.sendRedirect("showalbum.htm?albumid="+id+"&message=Add%20succesed");
			model.addAttribute("target","editphoto.htm");
			model.addAttribute("message","Add successed");
		}
		else
		{
			res.setIntHeader("sucess", 0);
			res.sendRedirect("showalbum.htm?albumid="+id+"&message=Add%20failed");
			model.addAttribute("target","addphoto.htm");
			model.addAttribute("message","Add failed");
		}
		model.addAttribute("photo",photo);
		return new ModelAndView("photomodify","model",model);
	}
	
	@RequestMapping(value="/editphoto.htm",method=RequestMethod.GET)
	protected ModelAndView handleShowEdit(HttpServletRequest req,
			HttpServletResponse res) throws Exception {
		// TODO Auto-generated method stub
		int userid=0;
		Photos photo=new Photos();
		if (CommonServices.getLoggedUsername(req)!=null)
			userid=userdao.getByName(CommonServices.getLoggedUsername(req)).getId();
		int photoid=CommonServices.getIDFromRequest(req, "photoid");
		if (photodao.get(photoid).getId()==userid)
		{
			photo=photodao.get(photoid);
		}
		ModelMap model =new ModelMap();
		model.addAttribute("target","editphoto.htm");
		model.addAttribute("message","please enter infomation");
		model.addAttribute("photo",photo);
		return new ModelAndView("photomodify","model",model);
	}
	
	@RequestMapping(value="/editphoto.htm",method=RequestMethod.POST)
	protected ModelAndView handelActEdit(HttpServletRequest req,HttpServletResponse res) throws Exception
	{
		Photos photo=getPhotoFromReq((MultipartHttpServletRequest) req);
		int photoid=CommonServices.getIDFromRequest(req, "photoid");
		ModelMap model=new ModelMap();
		if (photodao.edit(photo, photoid))
		{
			res.setIntHeader("sucess", 1);
			res.sendRedirect("showalbum.htm?albumid="+photoid+"&message=Edit%20succesed");
			model.addAttribute("target","editphoto.htm");
			model.addAttribute("message","Add successed");
		}
		else
		{
			res.setIntHeader("sucess", 0);
			res.sendRedirect("showalbum.htm?albumid="+photoid+"&message=Edit%20failed");
			model.addAttribute("target","editphoto.htm");
			model.addAttribute("message","Add failed");
		}
		model.addAttribute("photo",photo);
		return new ModelAndView("photomodify","model",model);
		
	}
	
	@RequestMapping(value="/joinphoto.htm")
	protected ModelAndView handelActJoin(HttpServletRequest req ,HttpServletResponse res) throws Exception
	{
		int pid=CommonServices.getIDFromRequest(req, "photoid");
		int rid=detaildao.get(userdao.getByName(CommonServices.getLoggedUsername(req)).getId(), competitiondao.getcurrent().getId()).getId();
		if(photodao.join(pid, rid))
		{
			res.setIntHeader("sucess", 1);
		}
		else
		{
			res.setIntHeader("sucess", 0);
		}
		return null;
	}
	
	@RequestMapping(value="/quitphoto.htm")
	protected ModelAndView handelActQuit(HttpServletRequest req ,HttpServletResponse res) throws Exception
	{
		int pid=CommonServices.getIDFromRequest(req, "photoid");
		int rid=detaildao.get(userdao.getByName(CommonServices.getLoggedUsername(req)).getId(), competitiondao.getcurrent().getId()).getId();
		if(photodao.quit(pid, rid))
		{
			res.setIntHeader("sucess", 1);
		}
		else
		{
			res.setIntHeader("sucess", 0);
		}
		return null;
	}
	
	@RequestMapping(value="/movephoto.htm")
	protected ModelAndView handelActMove(HttpServletRequest req ,HttpServletResponse res) throws Exception
	{
		int pid=CommonServices.getIDFromRequest(req, "photoid");
		int rid=CommonServices.getIDFromRequest(req, "newalbumid");
		if(photodao.quit(pid, rid))
		{
			res.setIntHeader("sucess", 1);
		}
		else
		{
			res.setIntHeader("sucess", 0);
		}
		return null;
	}
	
	@RequestMapping(value="/delphoto.htm")
	protected ModelAndView handelActDelete(HttpServletRequest req ,HttpServletResponse res) throws Exception
	{
		int pid=CommonServices.getIDFromRequest(req, "photoid");
		if(photodao.delete(pid))
		{
			res.setIntHeader("sucess", 1);
			res.sendRedirect("showalbum.htm?albumid="+pid+"&message=Del%20successed");
		}
		else
		{
			res.setIntHeader("sucess", 0);
			res.sendRedirect("showalbum.htm?albumid="+pid+"&message=Del%20failed");
		}
		return null;
	}
	
	@RequestMapping(value="/setpreview.htm")
	protected ModelAndView handelActSetPreview(HttpServletRequest req ,HttpServletResponse res) throws Exception
	{
		int pid=CommonServices.getIDFromRequest(req, "photoid");
		if(photodao.setPreview(pid))
		{
			res.setIntHeader("sucess", 1);
		}
		else
		{
			res.setIntHeader("sucess", 0);
		}
		return null;
	}
	
	@RequestMapping(value="/suggestphoto.htm")
	protected ModelAndView handelActSuggest(HttpServletRequest req ,HttpServletResponse res) throws Exception
	{
		int pid=CommonServices.getIDFromRequest(req, "photoid");
		if(photodao.suggest(pid))
		{
			res.setIntHeader("sucess", 1);
		}
		else
		{
			res.setIntHeader("sucess", 0);
		}
		return null;
	}
	
	@RequestMapping(value="/unsuggestphoto.htm")
	protected ModelAndView handelActUnsuggest(HttpServletRequest req ,HttpServletResponse res) throws Exception
	{
		int pid=CommonServices.getIDFromRequest(req, "photoid");
		if(photodao.unsuggest(pid))
		{
			res.setIntHeader("sucess", 1);
		}
		else
		{
			res.setIntHeader("sucess", 0);
		}
		return null;
	}

	@RequestMapping(value="/allsuggestedphoto.htm")
	protected ModelAndView handleShowAllSuggested(HttpServletRequest req,
			HttpServletResponse res) throws Exception {
		// TODO Auto-generated method stub
		ModelMap model=new ModelMap();
		model.addAttribute("message",CommonServices.getMessageFromRequest(req));
		model.addAttribute("target","/allsuggestedphotopage.htm");
		model.addAttribute("page",CommonServices.getPageFromRequest(req));
		return new ModelAndView("listajax","model",model);
	}
	
	@RequestMapping(value="/allsuggestedphotopage.htm")
	protected ModelAndView handleShowAllSuggestedContent(HttpServletRequest req,
			HttpServletResponse res) throws Exception {
		// TODO Auto-generated method stub
		String filtername="getphotoallsuggested";
		String sessionid=req.getSession().getId();
		if (CacheServices.getFromCache(cache, sessionid, filtername, 1)==null)
			CacheServices.insertToCache(cache, filtername, sessionid, photodao.getAllSuggested(), 10);
		int page=CommonServices.getPageFromRequest(req);
		List<Integer> photoids=CacheServices.getFromCache(cache, sessionid, filtername, page);
		List<Photos> photos=new ArrayList<Photos>();
		for(int i:photoids)
		{
			photos.add(photodao.get(i));
		}
		int resultcount=CacheServices.getCountFromCache(cache, sessionid, filtername);
		int pagecount=CommonServices.getPageFromCount(resultcount);
		int pageresultcount=photos.size();
		ModelMap model=new ModelMap();
		model.addAttribute("photo",photos);
		model.addAttribute("pageresultcount",pageresultcount);
		res.addIntHeader("resultcount", resultcount);
		res.addIntHeader("pagecount", pagecount);
		res.addIntHeader("currentpage", page);
		return new ModelAndView("photomain","model",model);
	}
	
	@RequestMapping(value="/showalbum.htm")
	protected ModelAndView handelShowAlbum (HttpServletRequest req,HttpServletResponse res)throws Exception
	{
		int albumid=CommonServices.getIDFromRequest(req, "albumid");
		String filtername="getalbum?id="+albumid+"";
		if (albumid==0)
		{
			filtername="getalbumall";
		}
		String sessionid=req.getSession().getId();
		CacheServices.insertToCache(cache, filtername, sessionid, photodao.getByAlbum(albumid), 10);
		ModelMap model=new ModelMap();
		model.addAttribute("message",CommonServices.getMessageFromRequest(req));
		model.addAttribute("target","/showalbumpage.htm?albumid="+albumid+"");
		model.addAttribute("page",CommonServices.getPageFromRequest(req));
		model.addAttribute("album",albumdao.get(albumid));
		return new ModelAndView("photoadmin","model",model);
	}
	
	@RequestMapping(value="/showalbumpage.htm")
	protected ModelAndView handelShowAlbumContent(HttpServletRequest req, HttpServletResponse res)
	{
		int albumid=CommonServices.getIDFromRequest(req, "albumid");
		String filtername="getalbum?id="+albumid+"";
		String sessionid=req.getSession().getId();
//		if (CacheServices.getFromCache(cache, sessionid, filtername, 1)==null)
//			CacheServices.insertToCache(cache, filtername, sessionid, photodao.getByAlbum(albumid), 10);
		int page=CommonServices.getPageFromRequest(req);
		List<Integer> photoids=CacheServices.getFromCache(cache, sessionid, filtername, page);
		List<Photos> photos=new ArrayList<Photos>();
		for(int i:photoids)
		{
			photos.add(photodao.get(i));
		}
		int resultcount=CacheServices.getCountFromCache(cache, sessionid, filtername);
		int pagecount=CommonServices.getPageFromCount(resultcount);
		int pageresultcount=photos.size();
		ModelMap model=new ModelMap();
		model.addAttribute("photo",photos);
		model.addAttribute("pageresultcount",pageresultcount);
		res.addIntHeader("resultcount", resultcount);
		res.addIntHeader("pagecount", pagecount);
		res.addIntHeader("currentpage", page);
		return new ModelAndView("albumphoto","model",model);
	}
	
	private Photos getPhotoFromReq(MultipartHttpServletRequest req)
	{
		Photos photo=new Photos();
		try {
			photo.setImage(req.getFile("image").getBytes());
			photo.setPreview(PhotoServices.getpreview(req.getFile("image").getBytes()));
			photo.setAlbumID(CommonServices.getIDFromRequest(req, "albumid"));
			photo.setDescription(req.getParameter("description"));
			photo.setLenth(PhotoServices.getHeight(req.getFile("image").getBytes()));
			photo.setWidth(PhotoServices.getwidth(req.getFile("image").getBytes()));
			photo.setName(req.getParameter("name"));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
		photo.setId(CommonServices.getIDFromRequest(req, "photoid"));
		return photo;
	}

}
